package com.example.study_manger.control;

import com.example.study_manger.entity.Organization;
import com.example.study_manger.pojo.PageOrganization;
import com.example.study_manger.service.OrganizationService;
import com.example.study_manger.tools.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/organizations")
public class OrganizationController {

    @Autowired
    private OrganizationService organizationService;
    @GetMapping
    public R<List<Organization>> getOrganizations() {
        List<Organization> organizations = organizationService.getAllOrganizations();
        return R.success(organizations);
    }
    @PostMapping("/ai")
   public R<String> askAI(@RequestBody Map<String,String> question) {
        System.out.println(question.get("question"));
        String s = organizationService.getAiResponse(question.get("question"));
        System.out.println(s);
        return R.success(s);
    }
    // 分页查询机构列表
    @GetMapping("/page")
    public R<PageOrganization> getOrganizations(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String type,
            @RequestParam(required = true) int page,
            @RequestParam(required = true) int size) {
        // 调用Service获取分页数据
        Page<Organization> page1 = organizationService.getOrganizations(name, type, page, size);
        PageOrganization pageOrganization = new PageOrganization(page1.getTotalElements(), page1.getContent());
        if (page1.isEmpty()) {
            return R.fail("没有更多数据了");           
        }
        return R.success(pageOrganization);
    }

    // 创建机构
    @PostMapping("/create")
    public R<Organization> createOrganization( @RequestBody Organization organization) {
        Organization organization1 = organizationService.createOrganization(organization);
        return R.success(organization1);
    }

    // 更新机构
    @PutMapping("/{id}")
    public R<Organization> updateOrganization(
            @PathVariable Long id,
            @RequestBody Organization organization) {
        Organization updatedOrganization = organizationService.updateOrganization(id, organization);
        return R.success(updatedOrganization);
    }

    // 删除机构
    @DeleteMapping("/{id}")
    public R<String> deleteOrganization(@PathVariable Long id) {
        String s = organizationService.deleteOrganization(id);
        if (s.equals("删除成功")) {
            return R.success(s);
        }return R.fail(s);
    }
}

